import React, { useState, useEffect, useCallback } from "react";
import "../../../styles/file.css";
import { Input, Space, Dropdown, Upload, Pagination, message } from "antd";
import Api from "../../../config/api/file";
import {
  SearchOutlined,
  LeftOutlined,
  RightOutlined,
  ArrowLeftOutlined,
  DownOutlined,
} from "@ant-design/icons";

// 图片导入
import fileIcon from "../../../assets/file/file.png";
import excelIcon from "../../../assets/file/excelIcon.png";
import wordIcon from "../../../assets/file/wordIcon.png";
import pptIcon from "../../../assets/file/pptIcon.png";
import demo from "../../../assets/file/demo.png";
import icon from "../../../assets/file/edit.png";
import add from "../../../assets/file/add.png";
import all from "../../../assets/file/all.png";
import recently from "../../../assets/file/recently.png";
import selectall from "../../../assets/file/selectall.png";
import selectrecently from "../../../assets/file/selectrecently.png";

import look from "../../../assets/file/look.png";
import upload from "../../../assets/file/upload.png";
import more from "../../../assets/file/more.png";
import selectlook from "../../../assets/file/selectlook.png";
import selectmore from "../../../assets/file/selectmore.png"

import feedback from "../../../assets/file/feedback.png";
import filter from "../../../assets/file/filter.png";
import excelLogo from "../../../assets/file/excelLogo.png";
import wordLogo from "../../../assets/file/wordLogo.png";
import PPTLogo from "../../../assets/file/PPTLogo.png";
import search from "../../../assets/file/search.png";
import back from "../../../assets/file/back.png";
import searchTwo from "../../../assets/file/searchTwo.png";
const { Search } = Input;

// 添加内联样式
const styles = {
  searchPopup: {
    position: 'absolute',
    top: '100%',
    left: 0,
    right: 0,
    backgroundColor: '#fff',
    boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
    borderRadius: '4px',
    zIndex: 1000,
    maxHeight: '600px',
    overflowY: 'auto',
    marginTop: '4px'
  },
  fileList: {
    margin: 0,
    padding: '8px 0',
    listStyle: 'none',
    maxHeight: '500px',
    overflowY: 'auto'
  },
  fileItem: {
    display: 'flex',
    alignItems: 'center',
    padding: '8px 16px',
    cursor: 'pointer',
    transition: 'background-color 0.3s',
    textAlign: 'left',
    '&:hover': {
      backgroundColor: '#f5f5f5'
    }
  },
  fileIcon: {
    width: '24px',
    height: '24px',
    marginRight: '12px'
  },
  fileMeta: {
    flex: 1,
    textAlign: 'left'
  },
  fileName: {
    fontSize: '14px',
    color: '#333',
    marginBottom: '4px',
    textAlign: 'left'
  },
  fileTime: {
    fontSize: '12px',
    color: '#999',
    textAlign: 'left'
  },
  fileLayerTitle: {
    padding: '8px 16px',
    fontSize: '14px',
    color: '#333',
    borderBottom: '1px solid #f0f0f0',
    textAlign: 'left'
  }
};

// 推荐项组件 - 用于展示搜索结果中的推荐文件样式
const RecommendationItem = ({ icon, title, desc, content, preview }) => {
  return (
    <div className="search_box_content_item">
      <div className="search_box_content_item_title">
        <div className="search_box_content_item_title_left">
          <div className="title_left">
            <img
              src={icon} // 文件类型图标
              style={{ width: "25px", height: "25px", marginTop: "8px" }}
              alt="" // 空 alt 属性，可根据实际情况添加描述
            />
          </div>
          <div>
            <div>{title}</div> {/* 文件标题 */}
            <div className="title_desc">{desc}</div> {/* 文件描述 */}
          </div>
        </div>
      </div>
      <div className="search_boxcontent">
        <div
          className="search_box_content_item_title_left"
          style={{ height: "45px" }}
        >
          <div className="title_left">
            <img
              src={excelIcon}
              style={
                {
                  width: "26px",
                  height: "25px",
                  marginTop: "8px",
                  marginLeft: "10px",
                }
              }
              alt="" // 空 alt 属性，可根据实际情况添加描述
            />
          </div>
          <div style={{ lineHeight: "45px", marginLeft: "5px" }}>
            <div>{content}</div> {/* 文件内容摘要 */}
          </div>
        </div>
        <div className="search_boxcontent_img">
          <img src={preview} style={{ width: "100%", height: "100%" }} alt="" /> {/* 预览图片 */}
        </div>
      </div>
    </div>
  );
};

// 推荐列表项组件 - 用于快速访问区域的文件展示
const RecommendationList = ({ file }) => {
  return (
    <div
      className="search_box_content_item"
      style={{ width: "220px", height: "250px" }}
      onClick={() => {
        window.open(file.ViewUrl, "_blank"); // 点击打开文件链接
      }}
    >
      <div className="search_boxcontent">
        <div className="search_boxcontent_img">
          <img
            src={file.PictureThumbnailURL} // 文件缩略图
            style={{ width: "100%", height: "100%" }}
            alt="" // 空 alt 属性，可根据实际情况添加描述
          />
        </div>
        <div className="search_box_content_item_title">
          <div className="search_box_content_item_title_left">
            <div className="title_left">
              <img
                src={ // 根据文件类型选择对应的图标
                  file.FileType == "docx"
                    ? wordIcon
                    : file.FileType == "xlsx"
                    ? excelIcon
                    : pptIcon
                }
                style={{ width: "25px", height: "25px", marginTop: "8px" }}
                alt="" // 空 alt 属性，可根据实际情况添加描述
              />
            </div>
            <div>
              <div>{file.Filename}</div> {/* 文件名 */}
              <div className="title_desc">{file.LastModifiedTime}</div> {/* 最后修改时间 */}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// 文件项组件 - 用于全部文件和最近打开列表的展示
const FileItem = ({ file }) => {
  return (
    <li
      className="file-item"
      onClick={() => {
        window.open(file.ViewUrl, "_blank"); // 点击打开文件链接
      }}
    >
      <img
        src={ // 根据文件类型选择对应的图标
          file.FileType == "docx"
            ? wordIcon
            : file.FileType == "xlsx"
            ? excelIcon
            : pptIcon
        }
        alt={file.FileType}
        className="file-icon"
      />
      <div className="file-meta">
        <div className="file-name">{file.Filename}</div> {/* 文件名 */}
      </div>
      <div className="time">{file.LastModifiedTime}</div> {/* 最后修改时间 */}
      {/* <div
        className="time"
        style={{
          width: "250px",
          display: "flex",
          alignItems: "center",
        }}
      >
        <img
          src={file.icon}
          style={{
            width: "17px",
            height: "17px",
            marginRight: "5px",
          }}
          alt="" // 空 alt 属性，可根据实际情况添加描述
        />
        {file.Editor}
      </div> */}
    </li>
  );
};

// 主组件：文档库页面逻辑
const TypewriterText = () => {
  // 状态管理
  const [searchValue, setSearchValue] = useState(""); // 搜索框的值
  const [activeTab, setActiveTab] = useState("all"); // 当前激活的快速访问标签 (全部/最近打开)
  const [sorttime, setsorttime] = useState(""); // 排序时间 (创建日期/修改日期)
  const [lastedittime, setlastedittime] = useState(""); // 最后编辑时间筛选条件
  const [activeTabs, setActiveTabs] = useState("全部"); // 搜索结果页面激活的标签 (全部/文件/站点)
  const [searchStatus, setSearchStatus] = useState(false); // 是否处于搜索结果页面状态
  const [isFocused, setIsFocused] = useState(false); // 搜索框是否聚焦
  const [selectedLabel, setSelectedLabel] = useState("文件类型"); // 文件类型筛选的当前选中标签
  const [selectedLabelTime, setSelectedLabelTime] = useState("最后修改时间"); // 时间筛选的当前选中标签
  const [selectedLabelend, setSelectedLabelend] = useState("排序依据 相关性(默认)"); // 排序依据的当前选中标签
  const [listStatus, setlistStatus] = useState(false); // 快速访问列表的显示模式 (列表/卡片)
  const [searchSiteList, setsearchSiteList] = useState([]); // 站点搜索结果列表 (目前未使用)
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const [fullQuickAccessData, setFullQuickAccessData] = useState([]); // All data for quick access
  const [fullSearchResultsData, setFullSearchResultsData] = useState([]); // All data for search results
  const [allFillList, setallFillList] = useState([]); // Paginated list for quick access
  const [SearchList, setSearchList] = useState([]); // Paginated list for search results
  const [popupResults, setPopupResults] = useState([]); // Results for the search popup

  // 快速访问标签列表配置
  const tabs = [
    { id: "all", icon: all, text: "全部", selecticon: selectall },
    { id: "recent", icon: recently, text: "最近打开", selecticon: selectrecently },
  ];

  // 上传组件属性配置
  const props = {
    name: "file",
    action: "https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload", // 上传接口地址
    headers: {
      authorization: "authorization-text",
    },
    onChange(info) { // 文件状态变化回调
      if (info.file.status !== "uploading") {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === "done") {
        message.success(`${info.file.name} file uploaded successfully`); // 上传成功提示
      } else if (info.file.status === "error") {
        message.error(`${info.file.name} file upload failed.`); // 上传失败提示
      }
    },
  };

  // 下拉菜单项配置
  const dropdownItems = {
    type: [ // 文件类型筛选
      { key: "1", label: "word" },
      { key: "2", label: "excel" },
      { key: "3", label: "powerpoint" },
    ],
    time: [ // 时间筛选
      { key: "1", label: "过去24小时内", value: "24hours" },
      { key: "2", label: "上周", value: "lastWeek" },
      { key: "3", label: "上个月", value: "lastMonth" },
      { key: "4", label: "过去三个月", value: "3months" },
      { key: "5", label: "过去一年", value: "1year" },
      { key: "6", label: "一年前", value: "over1year" },
    ],
    sort: [ // 排序依据
      { key: "1", label: "创建日期" },
      { key: "2", label: "修改日期" },
    ],
  };

  // 防抖搜索函数
  const debouncedSearch = useCallback(
    (value) => {
      if (value.trim()) {
        setPagination({
          ...pagination,
          current: 1
        });
        getSearchList(value, pagination.pageSize, "", "all", 1);
        setSearchStatus(true);
      } else {
        setSearchStatus(false);
        setIsFocused(false);
        getloadlist("", pagination.pageSize, false, "file", 1);
      }
    },
    [pagination]
  );

  // 处理搜索输入框内容变化
  const handleInputChange = (e) => {
    const value = e.target.value;
    setSearchValue(value);
    
    // 清除之前的定时器
    if (window.searchTimer) {
      clearTimeout(window.searchTimer);
    }
    
    // 设置新的定时器，1秒后执行搜索
    window.searchTimer = setTimeout(() => {
      if (value.trim()) {
        // 有搜索内容时，从本地数据过滤
        const searchLower = value.toLowerCase();
        const filteredResults = fullQuickAccessData.filter(item => {
          // 检查文件名（包括完整路径）
          if (item.Filename && item.Filename.toLowerCase().includes(searchLower)) {
            return true;
          }
          return false;
        });

        // 更新弹出框的搜索结果
        setPopupResults(filteredResults); // 显示所有匹配的结果
      } else {
        // 输入框为空时，显示全部数据
        setPopupResults(fullQuickAccessData);
        // Additionally, if the input is cleared, ensure the main quick access list is reset
        getloadlist("", pagination.pageSize, false, "file", 1);
      }
      setIsFocused(true); // 保持弹出框显示
    }, 1000);
  };

  // 处理搜索操作，点击搜索按钮或回车时触发
  const handleSearch = () => {
    if (searchValue.trim()) {
      // 直接使用已过滤的 popupResults 作为完整搜索结果的来源
      setFullSearchResultsData(popupResults); 

      setPagination({
        ...pagination,
        current: 1,
        total: popupResults.length,
      });

      // 手动分页 popupResults 的第一页到 SearchList
      const startIndex = 0;
      const endIndex = pagination.pageSize;
      const paginatedResults = popupResults.slice(startIndex, endIndex);
      setSearchList(paginatedResults);

      setSearchStatus(true);
      setIsFocused(false);
      setPopupResults([]); // 提交搜索后清空弹出框结果
    }
  };

  // 搜索输入框聚焦时触发
  const searchInputFocus = () => {
    setIsFocused(true);
    // 当输入框聚焦时，显示所有数据
    setPopupResults(fullQuickAccessData);
  };

  // 组件卸载时清除定时器
  useEffect(() => {
    return () => {
      if (window.searchTimer) {
        clearTimeout(window.searchTimer);
      }
    };
  }, []);

  // 获取搜索结果
  const getSearchList = async (search, rowLimit, sortByRecent, all, page = 1, lastedittime) => {
    try {
      var u = await Api._getcurrentUser();
      if (!u) return;

      // 获取所有1000条数据
      var datalist = await Api._getSearchData(
        search, // 传入搜索关键词
        1000,
        sortByRecent,
        all,
        1
      );

      // 处理返回的数据，格式化时间，生成预览URL
      const processedResults = datalist.results.map((item) => {
        const date = new Date(item.LastModifiedTime);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");

        const viewUrl = generateOfficeViewUrl(item);

        return {
          ...item,
          LastModifiedTime: `${year}年${month}月${day}日 ${hours}:${minutes}`,
          ViewUrl: viewUrl,
          CanViewOnline: canViewOnline(item.FileExtension),
        };
      });
      console.log('Processed Results:', processedResults);

      // 在所有数据中进行本地模糊搜索
      let filteredResults = processedResults;
      if (search) {
        const searchLower = search.toLowerCase();
        console.log('Search Term (lowercase):', searchLower);
        filteredResults = processedResults.filter(item => {
          // 检查文件名（包括完整路径）
          if (item.Filename && item.Filename.toLowerCase().includes(searchLower)) {
            return true;
          }
          return false;
        });
        console.log('Filtered Results (after local search):', filteredResults);
      }

      // Apply time filter if lastedittime is provided
      if (lastedittime) {
        filteredResults = filteredResults.filter(file => {
          const fileDate = new Date(file.LastModifiedTime);
          const now = new Date();
          
          switch (lastedittime) {
            case "24hours":
              return (now.getTime() - fileDate.getTime()) < 24 * 60 * 60 * 1000;
            case "lastWeek":
              return (now.getTime() - fileDate.getTime()) < 7 * 24 * 60 * 60 * 1000;
            case "lastMonth":
              return (now.getTime() - fileDate.getTime()) < 30 * 24 * 60 * 60 * 1000;
            case "3months":
              return (now.getTime() - fileDate.getTime()) < 90 * 24 * 60 * 60 * 1000;
            case "1year":
              return (now.getTime() - fileDate.getTime()) < 365 * 24 * 60 * 60 * 1000;
            case "over1year":
              return (now.getTime() - fileDate.getTime()) >= 365 * 24 * 60 * 60 * 1000;
            default:
              return true;
          }
        });
        console.log('Filtered Results (after time filter):', filteredResults);
      }

      // 保存完整的搜索结果到本地状态
      setFullSearchResultsData(filteredResults); // Store all filtered results

      // 计算分页
      const startIndex = (page - 1) * rowLimit;
      const endIndex = startIndex + rowLimit;
      const paginatedResults = filteredResults.slice(startIndex, endIndex);

      setSearchList(paginatedResults);
      setPagination({
        ...pagination,
        total: filteredResults.length,
        current: page,
      });
    } catch (error) {
      console.error("获取搜索结果失败:", error);
    }
  };

  // 取消搜索，回到初始状态
  const cacel = () => {
    setSearchStatus(false); // 退出搜索结果页面状态
    setIsFocused(false); // 取消聚焦
    setSearchValue(""); // 清空搜索值
    setPopupResults([]); // 清空弹出框数据
    // 重新加载快速访问列表的全部数据
    getloadlist("", pagination.pageSize, false, "file", 1); 
  };

  // 处理下拉菜单点击事件
  const handleMenuClick = (type) => ({ key }) => {
    const itemsMap = {
      type: dropdownItems.type,
      time: dropdownItems.time,
      sort: dropdownItems.sort,
    };
    const selectedItem = itemsMap[type].find((item) => item.key === key);
    
    // Update the selected label states first
    const setterMap = {
      type: setSelectedLabel,
      time: setSelectedLabelTime,
      sort: setSelectedLabelend,
    };
    setterMap[type](selectedItem.label);

    // Call tabclick to re-apply all filters, including the newly selected one
    tabclick(activeTabs); // Re-apply current active tab's filters
  };

  // 处理 Ant Design Search 组件的搜索事件 (通常是回车或点击搜索按钮)
  const onSearch = (value, _e, info) => console.log(info?.source, value);

  // 组件初始化时加载数据
  useEffect(() => {
    getloadlist("", pagination.pageSize, false, "file", pagination.current); // 加载全部文件列表
    getpeoplelist(); // 获取人员列表 (目前未使用)
    getsitelist(); // 获取站点列表 (目前未使用)
  }, []);

  // 获取站点搜索数据 (目前未在UI中直接使用)
  const getsitelist = async (search, rowLimit, sortByRecent) => {
    var u = await Api._getcurrentUser(); // 获取当前用户信息
    if (u != null) {
      var datalist = await Api._getSiteSearchData(search); // 调用 API 获取站点数据
      console.log("站点22,", datalist); // 打印站点数据
      setsearchSiteList(datalist.results); // 更新站点列表状态
    }
  };

  // 获取人员搜索数据 (目前未在UI中直接使用)
  const getpeoplelist = async (search, rowLimit, sortByRecent) => {
    var u = await Api._getcurrentUser(); // 获取当前用户信息
    if (u != null) {
      var datalist = await Api.getPeopleSearchData(); // 调用 API 获取人员数据
      console.log("人员1", datalist); // 打印人员数据
    }
  };

  // 加载文件列表的通用函数
  const getloadlist = async (search, rowLimit, sortByRecent, all, page = 1) => {
    try {
      var u = await Api._getcurrentUser(); // 获取当前用户信息
      if (!u) return; // 如果没有用户，则直接返回

      var datalist = await Api._getSearchData(
        search, // 搜索关键词
        1000, // 获取1000条数据
        sortByRecent, // 是否按最近修改时间排序
        all, // 文件类型筛选 (例如 'file'/'all')
        1 // 始终获取第一页，因为我们要获取所有数据
      );
      // 处理返回的数据，格式化时间，生成预览URL
      const processedResults = datalist.results.map((item) => {
        const date = new Date(item.LastModifiedTime);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");

        const viewUrl = generateOfficeViewUrl(item); // 生成Office文件在线预览URL

        return {
          ...item,
          LastModifiedTime: `${year}年${month}月${day}日 ${hours}:${minutes}`, // 格式化时间
          ViewUrl: viewUrl, // 在线预览URL
          CanViewOnline: canViewOnline(item.FileExtension), // 是否可以线上预览
        };
      });

      // 如果有搜索关键词，进行本地模糊搜索
      let filteredResults = processedResults;
      if (search) {
        filteredResults = processedResults.filter(item => 
          item.Filename.toLowerCase().includes(search.toLowerCase())
        );
      }
      
      setFullQuickAccessData(filteredResults); // Store all filtered results for quick access
      setPopupResults(filteredResults.slice(0, 10)); // Populate popup results with first 10 items

      // 计算分页
      const startIndex = (page - 1) * rowLimit;
      const endIndex = startIndex + rowLimit;
      const paginatedResults = filteredResults.slice(startIndex, endIndex);

      setallFillList(paginatedResults); // 更新当前页的文件列表
      setPagination({ // 更新分页信息
        ...pagination,
        total: filteredResults.length, // 使用过滤后的总数
        current: page,
      });
    } catch (error) {
      console.error("加载文件列表失败:", error);
    }
  };

  // 生成Office文件在线预览URL
  function generateOfficeViewUrl(item) {
    const { SiteName, UniqueId, Filename } = item; // 从item中解构所需属性
    const encodedFilename = encodeURIComponent(Filename); // 对文件名进行编码
    return `${SiteName}/_layouts/15/Doc.aspx?sourcedoc=${UniqueId.replace(
      /{|}/g,
      ""
    )}&file=${encodedFilename}&action=default`; // 构建URL
  }

  // 判断文件是否可以在线预览
  function canViewOnline(fileExtension) {
    // 首先检查 fileExtension 是否存在
    if (!fileExtension) return false;

    const supportedTypes = ["docx", "doc", "xlsx", "xls", "pptx", "ppt", "pdf"]; // 支持在线预览的文件类型
    return supportedTypes.includes(fileExtension.toLowerCase()); // 判断是否包含在支持类型中
  }

  // 处理快速访问标签点击事件 (全部/最近打开)
  const handleTabClick = (tabId, tabName) => {
    console.log(tabId, tabName);
    setActiveTab(tabId); // 设置当前激活的标签
    if (tabId == "all") { // 如果是"全部"标签
      getloadlist("", pagination.pageSize, false, "file", 1); // 加载全部文件
    } else { // 如果是"最近打开"标签
      getloadlist("", pagination.pageSize, true, "file", 1); // 加载最近打开文件
    }
  };

  // 处理分页改变
  const handlePageChanges = (page, pageSize) => {
    // 从本地数据中获取对应页的数据
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedResults = fullSearchResultsData.slice(startIndex, endIndex);

    setSearchList(paginatedResults);
    setPagination({
      ...pagination,
      current: page,
      pageSize,
    });
  };

  // 处理快速访问区域的分页改变事件
  const handlePageChange = (page, pageSize) => {
    // 从本地数据中获取对应页的数据
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedResults = fullQuickAccessData.slice(startIndex, endIndex);

    setallFillList(paginatedResults);
    setPagination({
      ...pagination,
      current: page,
      pageSize,
    });
  };

  // 搜索结果区域子标签点击事件 (全部/文件/站点)
  const tabclick = (tab) => {
    setActiveTabs(tab); // 更新激活的子标签

    let currentFilteredData = [...fullSearchResultsData]; // Start with the full search results

    // Apply tab-specific filtering
    if (tab === "文件") {
      currentFilteredData = currentFilteredData.filter(file => file.FileCategory !== "Site");
    } else if (tab === "站点") {
      currentFilteredData = currentFilteredData.filter(file => file.FileCategory === "Site");
    }

    // Re-apply existing type filter if any
    if (selectedLabel === "word") {
      currentFilteredData = currentFilteredData.filter(file =>
        file.FileType && (file.FileType.toLowerCase() === "docx" || file.FileType.toLowerCase() === "doc")
      );
    } else if (selectedLabel === "excel") {
      currentFilteredData = currentFilteredData.filter(file =>
        file.FileType && (file.FileType.toLowerCase() === "xlsx" || file.FileType.toLowerCase() === "xls")
      );
    } else if (selectedLabel === "powerpoint") {
      currentFilteredData = currentFilteredData.filter(file =>
        file.FileType && (file.FileType.toLowerCase() === "pptx" || file.FileType.toLowerCase() === "ppt")
      );
    }

    // Re-apply existing time filter if any
    if (selectedLabelTime && selectedLabelTime !== "最后修改时间") { // Check if a specific time filter is applied
      const timeFilterValue = dropdownItems.time.find(item => item.label === selectedLabelTime)?.value;
      if (timeFilterValue) {
        currentFilteredData = currentFilteredData.filter(file => {
          const fileDate = new Date(file.LastModifiedTime);
          const now = new Date();
          
          switch (timeFilterValue) {
            case "24hours":
              return (now.getTime() - fileDate.getTime()) < 24 * 60 * 60 * 1000;
            case "lastWeek":
              return (now.getTime() - fileDate.getTime()) < 7 * 24 * 60 * 60 * 1000;
            case "lastMonth":
              return (now.getTime() - fileDate.getTime()) < 30 * 24 * 60 * 60 * 1000;
            case "3months":
              return (now.getTime() - fileDate.getTime()) < 90 * 24 * 60 * 60 * 1000;
            case "1year":
              return (now.getTime() - fileDate.getTime()) < 365 * 24 * 60 * 60 * 1000;
            case "over1year":
              return (now.getTime() - fileDate.getTime()) >= 365 * 24 * 60 * 60 * 1000;
            default:
              return true;
          }
        });
      }
    }

    // Re-apply existing sort filter if any
    if (selectedLabelend === "修改日期") {
      currentFilteredData.sort((a, b) => new Date(b.LastModifiedTime) - new Date(a.LastModifiedTime));
    } else if (selectedLabelend === "创建日期") {
      // Assuming 'CreatedTime' for creation date, if not, it will sort by modification date as a fallback
      currentFilteredData.sort((a, b) => new Date(b.CreatedTime || b.LastModifiedTime) - new Date(a.CreatedTime || a.LastModifiedTime));
    }

    // Update SearchList with paginated results
    const startIndex = (pagination.current - 1) * pagination.pageSize;
    const endIndex = startIndex + pagination.pageSize;
    const paginatedResults = currentFilteredData.slice(startIndex, endIndex);

    setSearchList(paginatedResults);
    setPagination({
      ...pagination,
      total: currentFilteredData.length,
      current: 1, // Reset to first page when changing tabs
    });
  };

  // 根据 searchStatus 决定渲染快速访问页面还是搜索结果页面
  if (!searchStatus) {
    return (
      <div className="file_content">
        <div className="search_content">
          <div className="search_content_top">欢迎使用至一智能AI助手</div>
          <div
            className="search_content_bottom"
            style={{ position: "relative" }}
          >
            <Input
              value={searchValue}
              size="large"
              onChange={handleInputChange}
              placeholder="搜索"
              prefix={ // 前缀图标，根据聚焦状态显示返回或搜索图标
                isFocused ? (
                  <img
                    src={back}
                    alt="search"
                    style={{
                      width: "16px",
                      height: "16px",
                      marginRight: "8px",
                      cursor: "pointer",
                    }}
                    onClick={cacel} // 点击返回
                  />
                ) : (
                  <img
                    src={search}
                    alt="search"
                    style={{
                      width: "16px",
                      height: "16px",
                      marginRight: "8px",
                    }}
                  />
                )
              }
              suffix={ // 后缀图标，根据是否有搜索值显示搜索图标
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  {searchValue && (
                    <img
                      src={searchTwo}
                      alt="search"
                      style={{
                        width: "22px",
                        height: "22px",
                        cursor: "pointer",
                        marginRight: "8px"
                      }}
                      onClick={handleSearch} // 点击搜索
                    />
                  )}
                </div>
              }
              onPressEnter={handleSearch} // 回车键触发搜索
              onFocus={() => searchInputFocus()} // 聚焦时触发
              onBlur={() => setTimeout(() => setIsFocused(false), 200)} // 失焦时触发（延迟200ms）
              style={{
                boxShadow: "0px 2px 8.3px rgba(0, 0, 0, 0.15)",
                border: isFocused ? "1px solid #1890ff" : undefined, // 聚焦时边框变色
                borderRadius:"5px"
              }}
            />

            {isFocused && ( // 搜索框聚焦时显示文件推荐列表
              <div className="file_layer" style={styles.searchPopup}>
                <div style={styles.fileLayerTitle}>文件</div>
                <div className="recommendation-items">
                  <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                    <thead>
                      <tr>
                        <th style={{ padding: '8px 16px', textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>文件名称</th>
                        <th style={{ padding: '8px 16px', textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>最后修改时间</th>
                      </tr>
                    </thead>
                    <tbody>
                      {popupResults.map((file, index) => (
                        <tr
                          key={index}
                          style={{ cursor: 'pointer', borderBottom: '1px solid #f0f0f0' }}
                          onClick={() => {
                            window.open(file.ViewUrl || file.Path, "_blank");
                          }}
                        >
                          <td style={{ padding: '8px 16px', display: 'flex', alignItems: 'center' }}>
                            <img
                              src={ // 根据文件类型选择对应的图标
                                file.FileType == "docx"
                                  ? wordIcon
                                  : file.FileType == "xlsx"
                                  ? excelIcon
                                  : pptIcon
                              }
                              style={styles.fileIcon}
                              alt={file.FileType}
                            />
                            <div style={styles.fileName}>{file.Filename}</div>
                          </td>
                          <td style={{ padding: '8px 16px' }}>
                            <div style={styles.fileTime}>
                              {file.LastModifiedTime}
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            )}
          </div>
        </div>

        <div className="search_box">
          <div className="search_box_title" style={{ marginTop: "50px" }}>
            <div className="search_box_title_left">
              <div className="search_box_title_left">快速访问</div>
            </div>
          </div>

          <div className="file-manager-container">
            <div className="search_tab">
              <div style={{ display: "flex", alignItems: "center" }}>
                <div className="tabs-container"> {/* 快速访问标签容器 */}
                  {tabs.map((tab) => (
                    <button
                      key={tab.id}
                      className={`tab-item ${ // 标签项样式
                        activeTab === tab.id ? "active" : ""
                      }`}
                      onClick={() => handleTabClick(tab.id, tab.text)} // 点击标签切换
                    >
                      <img
                        src={activeTab === tab.id ? tab.selecticon : tab.icon} // 标签图标
                        className="tab-icon"
                        alt={tab.text}
                      />
                      <span className="tab-label">{tab.text}</span> {/* 标签文本 */}
                    </button>
                  ))}
                </div>
              </div>

              <div className="tabclass"> {/* 列表/卡片视图切换 */}
                <div className="tabclass">
                  <img
                    src={listStatus==false?selectlook:look} // 列表视图图标
                    style={{
                      width: "20px",
                      height: "12px",
                      marginLeft: "5px",
                      margin: "0 15px",
                      cursor: "pointer",
                    }}
                    alt="" // 空 alt 属性，可根据实际情况添加描述
                    onClick={() => setlistStatus(false)} // 切换到列表视图
                  />
                </div>
                <div className="tabclass">
                  <img
                 src={listStatus==true?selectmore:more} // 卡片视图图标
                    style={{
                      width: "30px",
                      height: "30px",
                      marginLeft: "5px",
                      cursor: "pointer",
                    }}
                    alt="" // 空 alt 属性，可根据实际情况添加描述
                    onClick={() => setlistStatus(true)} // 切换到卡片视图
                  />
                </div>
              </div>
            </div>
            {listStatus == false ? ( // 根据 listStatus 显示列表或卡片视图
              <ul className="file-list"> {/* 列表视图 */}
                {allFillList.map((file, index) => (
                  <FileItem key={index} file={file} /> // 文件项组件
                ))}
              </ul>
            ) : ( // 卡片视图
              <div className="search_box_content">
                {allFillList.map((file, index) => (
                  <RecommendationList key={index} file={file} /> // 推荐列表项组件
                ))}
              </div>
            )}
          </div>
        </div>
        <div className="file_pagination"> {/* 分页组件 */}
          <Pagination
            current={pagination.current}
            total={pagination.total}
            pageSize={pagination.pageSize}
            onChange={handlePageChange} // 页面改变回调
            showSizeChanger // 显示每页数量切换器
            showQuickJumper // 显示快速跳转
            showTotal={(total) => `共 ${total} 条`} // 显示总条数
            // 添加以下属性实现中文显示
            locale={{
              items_per_page: "条/页",
              jump_to: "跳至",
              jump_to_confirm: "确认",
              page: "页",
            }}
          />
        </div>
      </div>
    );
  }

  // 搜索结果页面渲染
  return (
    <div>
      <div className="second_search"> {/* 顶部搜索框 */}
        <Search
          prefix={ // 前缀图标，点击返回
            <div
              onClick={cacel}
              style={{
                cursor: "pointer",
                display: "flex",
                alignItems: "center",
                marginRight: 8,
              }}
            >
              <img
                src={back}
                alt="search"
                style={{
                  width: "22px",
                  height: "22px",
                  marginRight: "8px",
                }}
              />
            </div>
          }
          value={searchValue}
          placeholder="搜索" // 占位符
          onSearch={onSearch} // 点击搜索按钮或回车触发
          onChange={handleInputChange} // 输入框内容变化回调
          enterButton={ // 搜索按钮
            <div style={{ display: "flex", alignItems: "center" }}>
              <img
                src={searchTwo}
                alt="search"
                style={{ width: "22px", height: "22px", marginRight: "4px" }}
              />
            </div>
          }
          style={{
            boxShadow: "0px 2px 5px rgba(0, 0, 0, 0.1)", // Adjust to a lighter shadow
            
          }}
        />
      </div>

      <div style={{ width: "80%", margin: "0 auto" }}>
        <div className="tab_conent"> {/* 搜索结果子标签和反馈区域 */}
          <div className="tabs"> {/* 子标签 (全部/文件/站点) */}
            {["全部", "文件", "站点"].map((tab) => (
              <div
                key={tab}
                className={`tab ${activeTabs === tab ? "active" : ""}`}
                onClick={() => tabclick(tab)} // 点击子标签切换
              >
                {tab}
              </div>
            ))}
          </div>
          {/* <div className="tab_conent_right">
            <div className="tab_text">
              <img
                src={feedback}
                style={{ width: "15px", height: "16px", marginRight: "5px" }}
                alt=""
              />
              反馈
            </div>
            <div>搜索提示</div>
          </div> */}
        </div>

        {activeTabs == "文件" ? ( // 当选中"文件"子标签时显示筛选条件
          <div className="select"> {/* 筛选条件下拉菜单 */}
            <div style={{ display: "flex", alignItems: "center" }}>
              <Dropdown
                menu={{
                  items: dropdownItems.type,
                  onClick: handleMenuClick("type"),
                }}
                trigger={["hover"]}
              >
                <a
                  onClick={(e) => e.preventDefault()}
                  style={{
                    display: "inline-flex",
                    alignItems: "center",
                    gap: 8,
                  }}
                >
                  <span className="trigger-text">{selectedLabel}</span> {/* 文件类型筛选标签 */}
                  <DownOutlined
                    style={{ fontSize: 12, color: "rgba(0,0,0,0.6)" }}
                  />
                </a>
              </Dropdown>

              <div style={{ margin: "0 20px" }}>
                <Dropdown
                  menu={{
                    items: dropdownItems.time,
                    onClick: handleMenuClick("time"),
                  }}
                  trigger={["hover"]}
                >
                  <a
                    onClick={(e) => e.preventDefault()}
                    style={{
                      display: "inline-flex",
                      alignItems: "center",
                      gap: 8,
                    }}
                  >
                    <span className="trigger-text">{selectedLabelTime}</span> {/* 时间筛选标签 */}
                    <DownOutlined
                      style={{ fontSize: 12, color: "rgba(0,0,0,0.6)" }}
                    />
                  </a>
                </Dropdown>
              </div>
            </div>

            <div>
              <img
                style={{ width: "15px", height: "15px", marginRight: "5px" }}
                src={filter}
                alt="" // 空 alt 属性，可根据实际情况添加描述
              />
              <Dropdown
                menu={{
                  items: dropdownItems.sort,
                  onClick: handleMenuClick("sort"),
                }}
                trigger={["hover"]}
              >
                <a
                  onClick={(e) => e.preventDefault()}
                  style={{
                    display: "inline-flex",
                    alignItems: "center",
                    gap: 8,
                  }}
                >
                  <span className="trigger-text">{selectedLabelend}</span> {/* 排序依据标签 */}
                  <DownOutlined
                    style={{ fontSize: 12, color: "rgba(0,0,0,0.6)" }}
                  />
                </a>
              </Dropdown>
            </div>
          </div>
        ) : (
          <div></div>
        )}

        {/* <ul className="file-list">
          {searchSiteList.map((file, index) => (
            <li key={index} className="file-item">
              <img src={file.SiteLogo} className="file-icon" />
              <div
                className="file-meta"
                style={{ cursor: "pointer" }}
                onClick={() => {
                  window.open(file.Path, "_blank");
                }}
              >
                <div className="file-name">{file.Title}</div>
                <div className="second_time">{file.SiteName}</div>
              </div>
            </li>
          ))}
        </ul> */}

        <table style={{ width: '100%', borderCollapse: 'collapse', marginTop: '20px' }}>
          <thead>
            <tr>
              <th style={{ padding: '12px 16px', textAlign: 'left', borderBottom: '1px solid #e0e0e0', backgroundColor: '#f9f9f9' }}>文件名称</th>
              <th style={{ padding: '12px 16px', textAlign: 'left', borderBottom: '1px solid #e0e0e0', backgroundColor: '#f9f9f9' }}>最后修改时间</th>
              <th style={{ padding: '12px 16px', textAlign: 'left', borderBottom: '1px solid #e0e0e0', backgroundColor: '#f9f9f9' }}>摘要</th>
            </tr>
          </thead>
          <tbody>
            {SearchList.map((file, index) => {
              // 检查是否是文档（有FileExtension）
              if (file.FileCategory != "Site") { // 如果是文件类型
                return (
                  <tr
                    key={index}
                    style={{ cursor: "pointer", borderBottom: '1px solid #f0f0f0' }}
                    onClick={() => {
                      window.open(file.ViewUrl || file.Path, "_blank"); // 点击打开文件
                    }}
                  >
                    <td style={{ padding: '12px 16px', display: 'flex', alignItems: 'center' }}>
                      <img
                        src={ // 根据文件扩展名选择图标
                          file.FileExtension === "docx" ||
                          file.FileExtension === "doc"
                            ? wordIcon
                            : file.FileExtension === "xlsx" ||
                              file.FileExtension === "xls"
                            ? excelIcon
                            : pptIcon
                        }
                        className="file-icon-second"
                        alt="file icon"
                      />
                      <div className="file-name">
                        {file.Filename || file.Title} {/* 文件名或标题 */}
                      </div>
                    </td>
                    <td style={{ padding: '12px 16px' }}>
                      <div className="file-time">{file.LastModifiedTime}</div> {/* 最后修改时间 */}
                    </td>
                    <td style={{ padding: '12px 16px' }}>
                      <div className="second_time">{file.HitHighlightedSummary}</div> {/* 高亮摘要 */}
                    </td>
                  </tr>
                );
              }

              // 否则作为站点渲染
              return (
                <tr
                  key={index}
                  style={{ cursor: "pointer", borderBottom: '1px solid #f0f0f0' }}
                  onClick={() => {
                    window.open(file.Path, "_blank"); // 点击打开站点
                  }}
                >
                  <td style={{ padding: '12px 16px', display: 'flex', alignItems: 'center' }}>
                    <img
                      src={file.SiteLogo} // 站点Logo
                      className="file-icon-second"
                      alt="site icon"
                    />
                    <div className="file-name">{file.Title}</div> {/* 站点标题 */}
                  </td>
                  <td style={{ padding: '12px 16px' }}>
                    <div className="second_time">{file.SiteName}</div> {/* 站点名称 */}
                  </td>
                  <td style={{ padding: '12px 16px' }}></td> {/* Empty cell for consistency */}
                </tr>
              );
            })}
          </tbody>
        </table>

        <div
          className="file_pagination"
          style={{ margin: "20px 0", textAlign: "center" }}
        > {/* 搜索结果分页组件 */}
          <Pagination
            current={pagination.current}
            total={pagination.total}
            pageSize={pagination.pageSize}
            onChange={handlePageChanges} // 页面改变回调
            showSizeChanger // 显示每页数量切换器
            showQuickJumper // 显示快速跳转
            showTotal={(total) => `共 ${total} 条`} // 显示总条数
            locale={{
              items_per_page: "条/页",
              jump_to: "跳至",
              jump_to_confirm: "确认",
              page: "页",
            }}
          />
        </div>
      </div>
    </div>
  );
};

// 组件默认属性
TypewriterText.defaultProps = {
  homeInfo: {},
  listenPrintHtml: () => {},
};

export default TypewriterText;
